package cn.xxd.xxdwebportal.interceptor;

import cn.xxd.common.CookieUtils;
import cn.xxd.common.StringUtils;
import cn.xxd.entity.LoginUser;
import cn.xxd.entity.ReturnT;
import cn.xxd.xxdssointerface.AuthorityService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description: 用户登录处理拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Reference(version = "1.0.0", timeout = 100000)
    private AuthorityService authorityService;

    //@Value("${AUTHORITY}")
    //private String AUTHORITY;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
        // 前处理，执行handler之前执行此方法。
        //返回true，放行	false：拦截
        //1.从cookie中取authority
        String authority = CookieUtils.getCookieValue(request, "authority");

        //2.如果没有token，未登录状态，直接放行
        if (StringUtils.isBlank(authority)) {
            return true;
        }
        //3.取到token，需要调用sso系统的服务，根据token取用户信息
        ReturnT result = authorityService.getUserByToken(authority);
        //4.没有取到用户信息。登录过期，直接放行。
        if (result.getCode() != 200) {
            return true;
        }
        //5.取到用户信息。登录状态。
        LoginUser user = (LoginUser) result.getData();

        //6.把用户信息放到request中。只需要在Controller中判断request中是否包含user信息。放行
        request.setAttribute("user", user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
